import dayjs from 'dayjs'
import { addNum, subNum } from 'shiptools'
import { 
  getLineByVoyageNoApi, 
  getLineConfigApi, 
  getTripIntroductionApi, 
  getBoatIntroductionApi, 
  newLineIntroductionApi, 
  getCityLinePortApi, 
  getInsuranceConfigApi,
  getServiceNoticeApi   
} from '../../api/index'
import { channel, DATE_FORMAT, SHIP_SERVICE_TAG_DEFAULT, SHIP_PASSENGER_TYPE_NOTICE, PRODUCT_CODE, TRACER_PAGES } from '../../utils/constants'
import {asyncToast, Logger, showDayName, delayGetScrollOffset, delayGetClientRect, setPage, setEvent, queryString} from '../../utils/index'
const logger = new Logger()
const pageName = TRACER_PAGES['middle']
Page({

  /**
   * 页面的初始数据
   */
  data: {
    swiperHeight: 0,
    startLine: {},
    lineConfig: {},
    serviceFee: 0,
    serviceTags: [],
    toggle: false,
    isPleasureBoat: false,
    overDays: 0,
    
    departureTime: '',
    arrivalTime: '',
    transTime: '',

    lineIntroduction: {
        bannerList: [],
        tabsList: []
    },

    scrollIntoView: '',
    ticket: {},
    support: {},

    portInfo: {},

    // 车辆上船 选中
    isCarSelected: false,

    // 车船联运
    isTransportOpen: false,

    carInsuranceInfo: {},
    vehicleInsurances: [],
    currentCarInsurance: {},


    // 舱位相关
    seats: [],

    serviceNoticeOpen: false,
    inDep: false,
    currentNotice: {},
    serviceNotices: [],
    serviceFeeNotice: {},
    defaultServiceTags: SHIP_SERVICE_TAG_DEFAULT,
    passengerTypes: SHIP_PASSENGER_TYPE_NOTICE,

    // 地图
    currentIndex: 0,
    currentPort: {},
    portsList: [],

    reserveTicketOutDate: '',

    isServiceFeeOpened: false,
    wxrefid: '',

    previewImage: '',

    vstValue: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      query: options
    })
    
    const title = `${options.from}-${options.to}`
    if(options.from && options.to) {
      wx.setNavigationBarTitle({
        title: title
      })
    }

    this.init(options)
  },

  onShow: function() {
    const query = this.data.query
    setPage(pageName + '?' + queryString(query), PRODUCT_CODE)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('ship_truck');
  },

  onError: function (err) {
    setEvent('班次详情页', 'BC08', '^名称:'+err+'^')
  },

  init: function(options) {
    // 获取班次详情  
    this.getLineById(options)
  },

  /**
   * 是否游船线路
   * @param {Schedules} schedule 班次item
   * @returns {Boolean}
   */
  _isPleasureBoat: function(schedule) {
    return (schedule && schedule.NeedTripExplain) || (schedule && schedule.IsShowBoat)
  },


  getLineById: function({voyageSerialNo}) {
    const that = this
    getLineByVoyageNoApi({
      voyageSerialNo
    }).then(response => {
      if(!response || response.status !== 200) {
        return
      }
      if(!response.data || response.data.Code !== 10000) {
        logger.warn('停留太久..')

        // setEvent('班次详情页', 'BC07', `^出发城市:[出发城市名称]^到达城市:[到达城市名称]^是否白屏:[是/否]^港口航线:[港口航线名称]`)
        
        asyncToast({
          title: '停留时间过长，重新获取班次数据',
          icon: 'none',
          image: '',
          duration: 2000
        }).then(() => {
          wx.navigateBack()
        });
        return
      }

      // 设置去程nav标题
      const startLine = response.data.Data
      that.getLineConfig(startLine)
      const isPleasureBoat = that._isPleasureBoat(startLine)

      if(isPleasureBoat) {
        const newLineParams = {
          lineId: startLine.LineId,
          shipId: startLine.ShipId,
          shipName: startLine.ShipName,
          supplierId: startLine.SupplierId,
          voyageId: startLine.VoyageId
        }
        // 获取航线新介绍
        that.getNewLineIntroduction(newLineParams)
        // 获取航线旧的介绍
        that.getLineIntroduction(startLine)
          
      }


      const departureTimeDate = dayjs(startLine.DepartDateTime)
      const transTimeDate = dayjs(startLine.TransTime)

      const departureTime = departureTimeDate.format('HH:mm')
      const arrivalTime =  dayjs(startLine.ArriveDateTime).format('HH:mm')
      const transTime =  transTimeDate.format('HH:mm')
      // 换乘 跨天数
      let overDays = 0
      if(transTimeDate.get('year') === departureTimeDate.get('year') && transTimeDate.get('month') === departureTimeDate.get('month')) {
          overDays = subNum(transTimeDate.get('date'), departureTimeDate.get('date'))
      }

      const vstValue = `^出发港口:${startLine.DepartPort}^到达港口:${startLine.ArrivePort}^`

      that.setData({
        startLine,
        isPleasureBoat,
        overDays,
        departureTime,
        arrivalTime,
        transTime,
        vstValue
      })



    }).catch(error => {
      logger.warn(error)
    })
  },

  // 获取班次配置信息
  getLineConfig: function(startLine) {
    const that = this
    getLineConfigApi({
      LineId: startLine.LineId,
      DepartDate: startLine.DepartDateTime,
      Channel: channel
    }).then(response => {
      if(!response || response.status !== 200) {
        return
      }
      if(!response.data || response.data.Code !== 10000) {
        logger.warn('停留太久..')
        return
      }
      const lineConfig = response.data.Data

      
      // 航线服务费LineServiceFee 同程服务费TCLineServiceFee 优惠服务费Discount
      const serviceFee = addNum(lineConfig.LineServiceFee, lineConfig.TCLineServiceFee)

      let serviceTags = []
      if(lineConfig.LineServiceFee >  lineConfig.Deduction) {
        serviceTags.push(`预订立减${lineConfig.Deduction}元`)
      }
      if(lineConfig.LineServiceFee <=  lineConfig.Deduction) {
        serviceTags.push('减免全额服务费')
      }


      

      // 设置顶部信息
      that.setTicketInfo(startLine, lineConfig)

      that.setData({
        serviceFee,
        serviceTags,
        lineConfig
      })



    })
  },

  // 设置顶部信息
  setTicketInfo: function(startLine, lineConfig) {
    const that = this
    const isPleasureBoat = that._isPleasureBoat(startLine)
    const departDate = dayjs(startLine.DepartDateTime).format('MM月DD日')
    const departTime = dayjs(startLine.DepartDateTime).format('HH:mm')
    const arriveTime = dayjs(startLine.ArriveDateTime).format('HH:mm')

    const day = showDayName(startLine.DepartDateTime, !startLine.IsSerialVoyage)

    let title = startLine.IsSerialVoyage? '流水班 ': ''

    title = title + dayjs(startLine.DepartDateTime).format('MM-DD') + day

    const subTitle = ''
    const ticket = {
      title,
      subName: startLine.BoatSubProductName,
      departTime,
      arriveTime,
      departPort: startLine.DepartPort,
      arrivePort: startLine.ArrivePort,
    }

    const support = {
      car: lineConfig.SupportVehicle,
      truck: startLine.SupportHuoche === 1
    }

    if(isPleasureBoat) {
      ticket.title = startLine.BoatProductName || startLine.ArriveCity


      ticket.subTitle = `${departDate} ${departTime} 出发 ${startLine.DepartPort}-${startLine.ArrivePort}`
    }
    if(startLine.IsSerialVoyage) {
      ticket.subTitle = `流水班 首 ${departTime} 末 ${arriveTime} ${startLine.DepartPort}-${startLine.ArrivePort}`
    }
     
    let reserveTicketOutDate = ''
    if (startLine.IsReseverVoyage) {
      reserveTicketOutDate = this.getReserveTicketOutDate(startLine.DepartDateTime, startLine.PreSaleDays, startLine.ReserveDays)
      
    }

    if(support.car) {
      
      // 设置车辆上船car片
      that.getInsuranceConfig(startLine, lineConfig)
    }

    // 设置舱位列表
    that.setSeats(startLine, lineConfig)

    // 获取购票须知
    that.getServiceNotice(startLine, lineConfig)
   
    

    this.setData({
      ticket,
      support,
      reserveTicketOutDate
    }, () => {
      
        // 获取港口信息
        that.getCityLinePort(startLine)
    })
  },

  /**
     * 计算预约票出票时间
     * @param {String} departDate 出发时间
     * @param {Number} preSaleDays 预售天数（真实预售天数 + 预约天数）
     * @param {Number} reserveDays 预约天数
     * @returns {String} 出票日期
     */
    getReserveTicketOutDate (departDate, preSaleDays, reserveDays) {
      const diffDays =  preSaleDays - reserveDays - 1
      return dayjs(departDate).subtract(diffDays, 'day').format('MM月DD日')
  },

  // 设置舱位列表
  setSeats: function(startLine, lineConfig) {
    const seats = startLine.ShipSeats
    const seatImg = 'https://file.40017.cn/ship/ship/images/commons/default_seat.png'
    seats.forEach(item => {
      item.open = false
      item.seatImg = item.SeatPicture || seatImg
    })

    // BrokerSort
    seats.sort((a, b) => b.BrokerSort - a.BrokerSort)

    this.setData({
      seats
    })
  },

  // 获取游船介绍 有值就展示  游船介绍tag
  getNewLineIntroduction: function(params) {
    newLineIntroductionApi(params).then(response => {
      
      if(response.status !== 200) {
        logger.tips('网络错误')
        return
      }
      if(!response.data || response.data.code !== 10000) {
        logger.tips('请求失败或者没有数据')
        return
      }
      
      this.setData({
        isUseNewLineIntroduction: !!response.data.data
      })
    })
  },

  /**
   * 获取航线介绍信息
   * @param {Any} voyageInfo 班次详情
   */
  getLineIntroduction (voyageInfo) {
    const that = this
    if (voyageInfo.NeedTripExplain) { // 景点
        const params = {
            VoyageId: voyageInfo.VoyageId,
            SupplierId: voyageInfo.SupplierId,
            ShipName: voyageInfo.ShipName
        }
        that.getTripIntroduction(params)
        return
    }
    if (voyageInfo.IsShowBoat && voyageInfo.ShipId !== '0') { // 游船
        const params = {
            shipId: voyageInfo.ShipId
        }
        that.getBoatIntroduction(params)
    }
  },

  // 获取购票须知
  getServiceNotice: function(startLine, lineConfig) {
    const that = this
    const { LineId, DepartDateTime } = startLine
    getServiceNoticeApi({
      LineId,
      DepartDate: DepartDateTime,
      SeatName:""
    }).then(response => {
      if(!response || response.length <= 0) {
        return
      }

      const serviceFeeNotice = response.filter(item => item.NoticeType === 4)
      
      that.setData({
        serviceNotices: response,
        serviceFeeNotice
      })
    })
  },

  getTripIntroduction: function(params) {
    const that = this
    getTripIntroductionApi(params).then(response => {
      that.setData({
        lineIntroduction: response
      })
    })
  },

  getBoatIntroduction: function(params) {
    const that = this
    getBoatIntroductionApi(params).then(response => {
      if(!response) return
      that.setData({
        lineIntroduction: response
      })
    })
  },

  getCityLinePort: function({DepartCity, ArriveCity, DepartPort}) {
    const that = this
    // 获取城市港口列表
    getCityLinePortApi({DepartCity, ArriveCity})
    .then(response => {
      if(response.status !== 200) {
        logger.tips('网络错误')
        return
      }
      if(!response.data || response.data.Code !== 10000) {
        logger.tips('请求失败或者没有数据')
        return
      }
      const data = response.data.Data
      if (data) {
          // 查找所选班次的港口信息
          const portInfo = data.find(item => item.PortName === DepartPort)
          if (portInfo) {
            let ticket = that.data.ticket
            ticket.address = portInfo.PortAddress
            
            const currentPort = {
              id: portInfo.PortId,
              name: portInfo.PortName,
              address: portInfo.PortAddress,
              latitude: portInfo.PortLon,
              longitude: portInfo.PortLat,
              surrounding: portInfo.PortSurrounding
            }
            const center = currentPort
            const portsList = [currentPort]

            that.setData({
                ticket,
                currentPort: center,
                portsList
              })
          }
      }
    })
    .catch(error => {
        console.log('getCityLinePort函数', error)
    })
  },

  onOpenSeatList: function(e) {
    const startLine = this.data.startLine
    const seat = e.currentTarget.dataset.item
    const wxrefid = this.data.wxrefid

    if(startLine.IsReseverVoyage) {
      setEvent('班次详情页', 'BC16', `^渠道refid:${wxrefid}^航线名称:${startLine.DepartCity}-${startLine.ArriveCity}^船名:${startLine.ShipName}^舱位:${seat.DisplayName}^套餐名称:^套餐ID:^港口航线:${startLine.DepartPort}-${startLine.ArrivePort}^套餐位置:^类型:^`)
    } else {
      setEvent('班次详情页', 'BC04', `^渠道refid:${wxrefid}^航线名称:${startLine.DepartCity}-${startLine.ArriveCity}^船名:${startLine.ShipName}^舱位:${seat.DisplayName}^套餐名称:^套餐ID:^港口航线:${startLine.DepartPort}-${startLine.ArrivePort}^套餐位置:^类型:^`)
    }
    if(seat.TicketLeft <= 0) {
      logger.warn('余票不足')
      return
    }

    // 有增值服务走 下拉框， 目前不支持增值服务，直接购买跳转到 订单填写页
    const seatId = `${seat.SeatType}-${seat.SeatId}-${seat.DisplayName}`
    const checked = this.data.isCarSelected
    const isCarSelected = checked? '1': '0'

   
    wx.navigateTo({
      url: `../booking/index?voyageSerialNo=${startLine.VoyageSerialNo}&polyId=&serviceId=&seatId=${seatId}&isSelected=0&car=${isCarSelected}&pageFrom=midPage`
    })

    return

  },


  onTabBoat: function(e) {
    const href = e.currentTarget.dataset.href
    this.setData({
      scrollIntoView: href
    })
  },

  onGoBoatInfoPage: function() {
    const startLine = this.data.startLine
    const newLineParams = {
      lineId: startLine.LineId,
      shipId: startLine.ShipId,
      shipName: startLine.ShipName,
      supplierId: startLine.SupplierId,
      voyageId: startLine.VoyageId
    }
    wx.navigateTo({
      url: `../boatinfo/index?lineId=${newLineParams.lineId}&shipId=${newLineParams.shipId}&shipName=${newLineParams.shipName}&supplierId=${newLineParams.supplierId}&voyageId=${newLineParams.voyageId}`
    })

  },

  
  // 获取车辆保险
  getInsuranceConfig: function(startLine, lineConfig) {
    const that = this
    const { DepartDateTime, ArrivePort, DepartPort, LineId, ShipCode, SupplierId } = startLine

    getInsuranceConfigApi({
      ArrivePort,
      Channel: channel,
      DepartPort,
      DepartTime: DepartDateTime,

      // FIXME: refid 需要修改成腾讯出行船票插件端的 refid
      FromRefId: "464341607",
      LineId,
      ShipCode,
      SupplierId
    }).then(response => {
      if(!response || response.status !== 200) {
        return
      }
      if(!response.data || response.data.code !== 10000) {
          return
      }
      const carInsuranceInfo = response.data.data
      let currentCarInsurance = {}
      let currentCar = {}
      let isSoldOut = true
      // 过滤余票
      if(carInsuranceInfo.vehicleList && carInsuranceInfo.vehicleList.length > 0) {
        carInsuranceInfo.vehicleList = carInsuranceInfo.vehicleList.filter(item => {
            if(item.vehicleTicketLeft > 0) {
                item.name = `${item.vehicleTypeName}  ￥${item.vehicleTicketPrice}`
                return item
            }
        })
      }
      if(carInsuranceInfo.vehicleList.length > 0) {
          isSoldOut = false
      }
      if(carInsuranceInfo.vehicleList && carInsuranceInfo.vehicleList.length > 0) {
          currentCar = carInsuranceInfo.vehicleList[0]
      }

      let vehicleInsurances = carInsuranceInfo.vehicleInsurance && carInsuranceInfo.vehicleInsurance.vehicleInsurances || []

      let _insurances = []
      if(carInsuranceInfo.vehicleInsurance && vehicleInsurances && vehicleInsurances.length > 0) {
        let emptyInsurance = null
        let defaultInsurance = null
        carInsuranceInfo.vehicleInsurance.vehicleInsurances.forEach(item => {
            if(item.insuranceId === 0) {
                emptyInsurance = item
            } else {
                if(item.isDefault === 1) {
                    defaultInsurance = item
                } else {
                    _insurances.push(item)
                }
            }
        })

        // 默认保险排序第一个
        if(defaultInsurance) {
            _insurances.unshift(defaultInsurance)
        }

        // 默认不购买保险排序最后
        if(emptyInsurance) {
            _insurances.push(emptyInsurance)
        }

        carInsuranceInfo.vehicleInsurance.vehicleInsurances = _insurances
        
        const filterCurrCars = carInsuranceInfo.vehicleInsurance.vehicleInsurances.filter(item => item.isDefault === 1)
        if(filterCurrCars && filterCurrCars.length > 0 && isEmpty(currentCarInsurance)) {
          currentCarInsurance = filterCurrCars[0]
        }
      
      }

      // 计算最终价格
      that.setData({
        carInsuranceInfo: carInsuranceInfo,
        currentCarInsurance,
        vehicleInsurances: _insurances
      }, () => {
        
      })

    })
  },

  onToggleCar: function(e) {
    // isCarSelected
    const _isCarSelected = this.data.isCarSelected
    this.setData({
      isCarSelected: !_isCarSelected
    })
  },

  closeLineService: function() {
    this.setData({
      serviceNoticeOpen: false    
    })
  },

  onServiceNotice: function(e) {
    const item = e.currentTarget.dataset.item || e.detail
    this.setData({
      serviceNoticeOpen: true,
      currentNotice: item
    })

    let eventLabel = ''
    switch(item.NoticeType) {
      case 1:
        eventLabel = '购票'
        break;
      case 2:
        eventLabel = '取票'
        break;
      case 3:
        eventLabel = '退改'
        break;
      case 4:
        break;
      
      default:
        break;
    }
    
    if(eventLabel) {
      setEvent('列表', 'BC25', `^服务须知:${eventLabel}^`)
    }

  },

  openCarTip: function() {
    const isTransportOpen = this.data.isTransportOpen
    this.setData({
      isTransportOpen: !isTransportOpen
    })
  },

  
  goToMap: function() {
    const startLine = this.data.startLine
    if(!startLine) return
    const departCity = startLine.DepartCity
    const arriveCity = startLine.ArriveCity
    const departPort = startLine.DepartPort
    const arrivePort = startLine.ArrivePort
    const lineId = startLine.LineId
    const isPort = !departCity && !arriveCity ? '1' : '0' // 是否通过港口查询
    const url = `../map/index?from=${departCity || departPort}&to=${arriveCity || arrivePort}&fromPort=${departPort}&toPort=${arrivePort}&lineId=${lineId}&isPort=${isPort}&canOrder=list`
    wx.navigateTo({
      url
    })

    setEvent('列表', 'BC03', `^航线名称:${departCity}-${arriveCity}^`)
  },

  handleMarkerClick: function() {
    this.goToMap()
  },
  handleLabelClick: function() {
    this.goToMap()
  },
  handleSetCenter: function() {
    this.goToMap()
  },

  
  // tab点击
  handleTabClick (e) {
    const index = e.currentTarget.dataset.index
    const { lineIntroduction, vstValue } = this.data
    const tabsList = lineIntroduction.tabsList
    const href = `${tabsList[index].href}`
    const title = tabsList[index].title
    if(title === '游船简介') {
        setEvent('班次详情页', 'BC11', vstValue)
    } else if(title === '景点介绍') {
        setEvent('班次详情页', 'BC12', vstValue)
    } else if(title === '港口地址') {
        setEvent('班次详情页', 'BC13', vstValue)
    } else if(title === '行程介绍') {
        setEvent('班次详情页', 'BC17', '')
    } else if(title === '费用包含') {
        setEvent('班次详情页', 'BC18', '')
    }
    
    // this.scrollToTarget(href)
    this.setData({
      currentIndex: index,
      scrollIntoview: href
    })
   
  },

  
  // 跳到锚点
  scrollToTarget (href) {
    // H5无法获取滚动高度，区分环境计算。
    delayGetScrollOffset({delayTime: 0})
    .then(val => {
        delayGetClientRect({self: this, selectorStr: href, delayTime: 0})
        .then(rect => {
          if(rect[0]) {
            const top = rect[0].top // 所选元素距离窗口顶部距离
            
            let scrollTop = 0 // 页面已滚动高度
            if(val[0]) {
              scrollTop = val[0].scrollTop
            }
            let delta = 47 // tab的高度
      
            wx.pageScrollTo({ // 滚动到窗口顶部
                selector: '.middle-scroll',
                scrollTop: top + scrollTop - delta,
                duration: 300
            })
          }
        })
    })
  },

  closeServiceFeeDialog: function() {
    this.setData({
      isServiceFeeOpened: false
    })
  },

  onServiceFee: function() {
    this.setData({
      isServiceFeeOpened: true
    })
  },

  
  imgLoad: function(e) {
    let _height = e.detail.height * (750 / e.detail.width)
    if(_height < this.data.swiperHeight || this.data.swiperHeight == 0){
        this.setData({
            swiperHeight: _height
        })
    }
  },
  
  imageLoadErr: function(err) {
  },


  onShowSeatImg: function(e) {
    const img = e.currentTarget.dataset.img
    const seat = e.currentTarget.dataset.seat
    
    setEvent('班次详情页', 'BC21', `^舱位:${seat}`)
    if(!img) return
    this.setData({
      previewImage: img
    })
  },

  onHidePreview: function() {
    this.setData({
      previewImage: ''
    })
  }

})